<template>
  <div class="classification-page">
    <!-- 筛选条件 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="分析类型">
          <el-select
            v-model="filterForm.type"
            placeholder="选择分析类型"
            style="width: 200px"
            @change="handleTypeChange"
          >
            <el-option label="总体分类统计" value="overall" />
            <el-option label="按班级分类" value="by-class" />
            <el-option label="按课程分类" value="by-course" />
            <el-option label="交叉分析(班级×课程)" value="cross" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择班级" v-if="filterForm.type === 'overall' || filterForm.type === 'by-course'">
          <el-select
            v-model="filterForm.class"
            placeholder="全部班级"
            clearable
            style="width: 180px"
            @change="loadClassification"
          >
            <el-option
              v-for="cls in classes"
              :key="cls"
              :label="cls"
              :value="cls"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择课程" v-if="filterForm.type === 'overall' || filterForm.type === 'by-class'">
          <el-select
            v-model="filterForm.course"
            placeholder="平均成绩"
            clearable
            style="width: 180px"
            @change="loadClassification"
          >
            <el-option
              v-for="course in courses"
              :key="course"
              :label="course"
              :value="course"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadClassification">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 总体分类统计 -->
    <div v-if="filterForm.type === 'overall' && data.type === 'overall'">
      <el-card shadow="hover" class="summary-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><PieChart /></el-icon>
              总体分类统计
            </span>
            <div>
              <el-tag type="info">{{ data.scope?.class || '全部班级' }}</el-tag>
              <el-tag type="primary" style="margin-left: 10px">{{ data.scope?.course || '平均成绩' }}</el-tag>
            </div>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :xs="12" :sm="8" :md="4">
            <el-statistic title="总人数" :value="data.summary?.total || 0">
              <template #suffix>人</template>
            </el-statistic>
          </el-col>
          <el-col :xs="12" :sm="8" :md="4">
            <el-statistic title="优秀" :value="data.summary?.excellent || 0" class="excellent">
              <template #suffix>人 ({{ data.summary?.excellentRate || 0 }}%)</template>
            </el-statistic>
          </el-col>
          <el-col :xs="12" :sm="8" :md="4">
            <el-statistic title="良好" :value="data.summary?.good || 0" class="good">
              <template #suffix>人 ({{ data.summary?.goodRate || 0 }}%)</template>
            </el-statistic>
          </el-col>
          <el-col :xs="12" :sm="8" :md="4">
            <el-statistic title="中等" :value="data.summary?.medium || 0" class="medium">
              <template #suffix>人 ({{ data.summary?.mediumRate || 0 }}%)</template>
            </el-statistic>
          </el-col>
          <el-col :xs="12" :sm="8" :md="4">
            <el-statistic title="及格" :value="data.summary?.pass || 0" class="pass">
              <template #suffix>人 ({{ data.summary?.passRate || 0 }}%)</template>
            </el-statistic>
          </el-col>
          <el-col :xs="12" :sm="8" :md="4">
            <el-statistic title="不及格" :value="data.summary?.fail || 0" class="fail">
              <template #suffix>人 ({{ data.summary?.failRate || 0 }}%)</template>
            </el-statistic>
          </el-col>
        </el-row>
      </el-card>

      <!-- 各等级学生列表 -->
      <el-row :gutter="20" class="details-row">
        <el-col :xs="24" :md="12" :lg="8" v-for="(grade, key) in data.details" :key="key">
          <el-card shadow="hover" :class="`grade-card grade-${key}`">
            <template #header>
              <div class="grade-header">
                <span>{{ getGradeName(key) }}</span>
                <el-tag :type="getGradeType(key)">{{ grade.length }}人</el-tag>
              </div>
            </template>
            <el-table :data="grade.slice(0, 10)" size="small" max-height="300">
              <el-table-column prop="studentId" label="学号" width="100" />
              <el-table-column prop="name" label="姓名" width="80" />
              <el-table-column prop="class" label="班级" show-overflow-tooltip />
              <el-table-column prop="score" label="成绩" width="70" align="center">
                <template #default="{ row }">
                  <el-tag :type="getScoreType(row.score)" size="small">{{ row.score }}</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="grade.length > 10" class="more-tip">
              还有 {{ grade.length - 10 }} 名学生...
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 按班级分类 -->
    <div v-if="filterForm.type === 'by-class' && data.type === 'by-class'">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><School /></el-icon>
              按班级分类统计
            </span>
            <el-tag type="primary">{{ data.course || '平均成绩' }}</el-tag>
          </div>
        </template>

        <el-table :data="data.data" stripe>
          <el-table-column prop="class" label="班级" width="120" fixed />
          <el-table-column prop="total" label="人数" width="80" align="center" />
          <el-table-column prop="average" label="平均分" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="getScoreType(row.average)">{{ row.average }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="优秀(90-100)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.excellent }}人 ({{ row.rates.excellentRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="良好(80-89)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.good }}人 ({{ row.rates.goodRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="中等(70-79)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.medium }}人 ({{ row.rates.mediumRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="及格(60-69)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.pass }}人 ({{ row.rates.passRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="不及格(<60)" width="120" align="center">
            <template #default="{ row }">
              <span style="color: #F56C6C; font-weight: bold;">
                {{ row.distribution.fail }}人 ({{ row.rates.failRate }}%)
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 图表展示 -->
      <el-card shadow="hover" style="margin-top: 20px">
        <template #header>
          <span>班级成绩分布对比</span>
        </template>
        <div ref="classChart" style="height: 400px"></div>
      </el-card>
    </div>

    <!-- 按课程分类 -->
    <div v-if="filterForm.type === 'by-course' && data.type === 'by-course'">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><Document /></el-icon>
              按课程分类统计
            </span>
            <el-tag type="info">{{ data.class || '全部班级' }}</el-tag>
          </div>
        </template>

        <el-table :data="data.data" stripe>
          <el-table-column prop="course" label="课程" width="120" fixed />
          <el-table-column prop="total" label="人数" width="80" align="center" />
          <el-table-column prop="average" label="平均分" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="getScoreType(row.average)">{{ row.average }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="优秀(90-100)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.excellent }}人 ({{ row.rates.excellentRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="良好(80-89)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.good }}人 ({{ row.rates.goodRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="中等(70-79)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.medium }}人 ({{ row.rates.mediumRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="及格(60-69)" width="120" align="center">
            <template #default="{ row }">
              {{ row.distribution.pass }}人 ({{ row.rates.passRate }}%)
            </template>
          </el-table-column>
          <el-table-column label="不及格(<60)" width="120" align="center">
            <template #default="{ row }">
              <span style="color: #F56C6C; font-weight: bold;">
                {{ row.distribution.fail }}人 ({{ row.rates.failRate }}%)
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 图表展示 -->
      <el-card shadow="hover" style="margin-top: 20px">
        <template #header>
          <span>课程成绩分布对比</span>
        </template>
        <div ref="courseChart" style="height: 400px"></div>
      </el-card>
    </div>

    <!-- 交叉分析 -->
    <div v-if="filterForm.type === 'cross' && data.type === 'cross'">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">
              <el-icon><Grid /></el-icon>
              交叉分析 (班级 × 课程)
            </span>
          </div>
        </template>

        <el-tabs v-model="activeTab">
          <el-tab-pane label="平均分矩阵" name="average">
            <el-table :data="data.matrix" border stripe>
              <el-table-column prop="class" label="班级/课程" width="120" fixed />
              <el-table-column 
                v-for="course in data.courses" 
                :key="course" 
                :label="course" 
                align="center"
                width="100"
              >
                <template #default="{ row }">
                  <el-tag 
                    v-if="row.courses[course]?.total > 0"
                    :type="getScoreType(row.courses[course]?.average)"
                    size="small"
                  >
                    {{ row.courses[course]?.average }}
                  </el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="等级分布" name="distribution">
            <el-collapse v-model="activeClasses">
              <el-collapse-item 
                v-for="classItem in data.matrix" 
                :key="classItem.class" 
                :name="classItem.class"
              >
                <template #title>
                  <strong>{{ classItem.class }}</strong>
                </template>
                <el-table :data="Object.keys(classItem.courses).map(c => ({ 
                  course: c, 
                  ...classItem.courses[c] 
                }))" stripe>
                  <el-table-column prop="course" label="课程" width="120" />
                  <el-table-column prop="total" label="人数" width="80" align="center" />
                  <el-table-column prop="average" label="平均分" width="90" align="center">
                    <template #default="{ row }">
                      <el-tag :type="getScoreType(row.average)">{{ row.average }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="优秀" width="80" align="center">
                    <template #default="{ row }">
                      {{ row.distribution?.excellent || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="良好" width="80" align="center">
                    <template #default="{ row }">
                      {{ row.distribution?.good || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="中等" width="80" align="center">
                    <template #default="{ row }">
                      {{ row.distribution?.medium || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="及格" width="80" align="center">
                    <template #default="{ row }">
                      {{ row.distribution?.pass || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="不及格" width="80" align="center">
                    <template #default="{ row }">
                      <span style="color: #F56C6C; font-weight: bold;">
                        {{ row.distribution?.fail || 0 }}
                      </span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 热力图 -->
      <el-card shadow="hover" style="margin-top: 20px">
        <template #header>
          <span>成绩热力图</span>
        </template>
        <div ref="heatmapChart" style="height: 500px"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getClassification } from '@/api/analysis'
import { getClasses } from '@/api/student'
import axios from 'axios'

const filterForm = reactive({
  type: 'overall',
  class: '',
  course: ''
})

const classes = ref([])
const courses = ref([])
const data = ref({})
const activeTab = ref('average')
const activeClasses = ref([])

const classChart = ref()
const courseChart = ref()
const heatmapChart = ref()

let classChartInstance = null
let courseChartInstance = null
let heatmapChartInstance = null

// 加载班级列表
const loadClasses = async () => {
  try {
    const res = await getClasses()
    classes.value = res.data
  } catch (error) {
    console.error('加载班级列表失败:', error)
  }
}

// 加载课程列表
const loadCourses = async () => {
  try {
    const res = await axios.get('/api/students/filter/courses')
    courses.value = res.data.data
  } catch (error) {
    console.error('加载课程列表失败:', error)
  }
}

// 加载分类统计数据
const loadClassification = async () => {
  try {
    const params = { type: filterForm.type }
    
    if (filterForm.class) params.class = filterForm.class
    if (filterForm.course) params.course = filterForm.course
    
    const res = await getClassification(params)
    data.value = res.data
    
    // 渲染图表
    await nextTick()
    if (filterForm.type === 'by-class') renderClassChart()
    if (filterForm.type === 'by-course') renderCourseChart()
    if (filterForm.type === 'cross') renderHeatmapChart()
    
    ElMessage.success('数据加载成功')
  } catch (error) {
    ElMessage.error('加载分类统计数据失败')
  }
}

// 类型改变
const handleTypeChange = () => {
  filterForm.class = ''
  filterForm.course = ''
  loadClassification()
}

// 渲染班级对比图表
const renderClassChart = () => {
  if (!classChart.value || !data.value.data) return
  
  if (!classChartInstance) {
    classChartInstance = echarts.init(classChart.value)
  }
  
  const classes = data.value.data.map(d => d.class)
  const excellent = data.value.data.map(d => d.distribution.excellent)
  const good = data.value.data.map(d => d.distribution.good)
  const medium = data.value.data.map(d => d.distribution.medium)
  const pass = data.value.data.map(d => d.distribution.pass)
  const fail = data.value.data.map(d => d.distribution.fail)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['优秀', '良好', '中等', '及格', '不及格']
    },
    xAxis: {
      type: 'category',
      data: classes
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      { name: '优秀', type: 'bar', stack: 'total', data: excellent, itemStyle: { color: '#67C23A' } },
      { name: '良好', type: 'bar', stack: 'total', data: good, itemStyle: { color: '#409EFF' } },
      { name: '中等', type: 'bar', stack: 'total', data: medium, itemStyle: { color: '#E6A23C' } },
      { name: '及格', type: 'bar', stack: 'total', data: pass, itemStyle: { color: '#F56C6C' } },
      { name: '不及格', type: 'bar', stack: 'total', data: fail, itemStyle: { color: '#909399' } }
    ]
  }
  
  classChartInstance.setOption(option)
}

// 渲染课程对比图表
const renderCourseChart = () => {
  if (!courseChart.value || !data.value.data) return
  
  if (!courseChartInstance) {
    courseChartInstance = echarts.init(courseChart.value)
  }
  
  const courses = data.value.data.map(d => d.course)
  const excellent = data.value.data.map(d => d.distribution.excellent)
  const good = data.value.data.map(d => d.distribution.good)
  const medium = data.value.data.map(d => d.distribution.medium)
  const pass = data.value.data.map(d => d.distribution.pass)
  const fail = data.value.data.map(d => d.distribution.fail)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['优秀', '良好', '中等', '及格', '不及格']
    },
    xAxis: {
      type: 'category',
      data: courses
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      { name: '优秀', type: 'bar', stack: 'total', data: excellent, itemStyle: { color: '#67C23A' } },
      { name: '良好', type: 'bar', stack: 'total', data: good, itemStyle: { color: '#409EFF' } },
      { name: '中等', type: 'bar', stack: 'total', data: medium, itemStyle: { color: '#E6A23C' } },
      { name: '及格', type: 'bar', stack: 'total', data: pass, itemStyle: { color: '#F56C6C' } },
      { name: '不及格', type: 'bar', stack: 'total', data: fail, itemStyle: { color: '#909399' } }
    ]
  }
  
  courseChartInstance.setOption(option)
}

// 渲染热力图
const renderHeatmapChart = () => {
  if (!heatmapChart.value || !data.value.matrix) return
  
  if (!heatmapChartInstance) {
    heatmapChartInstance = echarts.init(heatmapChart.value)
  }
  
  const classes = data.value.classes
  const courses = data.value.courses
  const heatmapData = []
  
  data.value.matrix.forEach((classItem, classIndex) => {
    courses.forEach((course, courseIndex) => {
      const avg = classItem.courses[course]?.average || 0
      heatmapData.push([courseIndex, classIndex, avg])
    })
  })
  
  const option = {
    tooltip: {
      position: 'top',
      formatter: (params) => {
        return `${classes[params.value[1]]}<br/>${courses[params.value[0]]}: ${params.value[2]}`
      }
    },
    grid: {
      left: 100,
      right: 50,
      top: 50,
      bottom: 80
    },
    xAxis: {
      type: 'category',
      data: courses,
      splitArea: { show: true }
    },
    yAxis: {
      type: 'category',
      data: classes,
      splitArea: { show: true }
    },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 20,
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    series: [{
      name: '平均分',
      type: 'heatmap',
      data: heatmapData,
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  heatmapChartInstance.setOption(option)
}

// 获取等级名称
const getGradeName = (key) => {
  const names = {
    excellent: '优秀 (90-100分)',
    good: '良好 (80-89分)',
    medium: '中等 (70-79分)',
    pass: '及格 (60-69分)',
    fail: '不及格 (<60分)'
  }
  return names[key]
}

// 获取等级类型
const getGradeType = (key) => {
  const types = {
    excellent: 'success',
    good: '',
    medium: 'warning',
    pass: 'danger',
    fail: 'info'
  }
  return types[key]
}

// 获取分数标签类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  if (score >= 60) return 'danger'
  return 'info'
}

// 监听窗口大小变化
const handleResize = () => {
  classChartInstance?.resize()
  courseChartInstance?.resize()
  heatmapChartInstance?.resize()
}

onMounted(() => {
  loadClasses()
  loadCourses()
  loadClassification()
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.classification-page {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.filter-card {
  margin-bottom: 20px;
}

.summary-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.details-row {
  margin-bottom: 20px;
}

.grade-card {
  margin-bottom: 20px;
}

.grade-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.grade-card.grade-excellent :deep(.el-card__header) {
  background: #f0f9ff;
  border-bottom: 2px solid #67C23A;
}

.grade-card.grade-good :deep(.el-card__header) {
  background: #f0f9ff;
  border-bottom: 2px solid #409EFF;
}

.grade-card.grade-medium :deep(.el-card__header) {
  background: #fdf6ec;
  border-bottom: 2px solid #E6A23C;
}

.grade-card.grade-pass :deep(.el-card__header) {
  background: #fef0f0;
  border-bottom: 2px solid #F56C6C;
}

.grade-card.grade-fail :deep(.el-card__header) {
  background: #f4f4f5;
  border-bottom: 2px solid #909399;
}

.more-tip {
  text-align: center;
  color: #909399;
  padding: 10px;
  font-size: 14px;
}

.excellent :deep(.el-statistic__number) {
  color: #67C23A;
}

.good :deep(.el-statistic__number) {
  color: #409EFF;
}

.medium :deep(.el-statistic__number) {
  color: #E6A23C;
}

.pass :deep(.el-statistic__number) {
  color: #F56C6C;
}

.fail :deep(.el-statistic__number) {
  color: #909399;
}
</style>
